package com.pand.util;

import java.text.DecimalFormat;
import java.util.Date;

/**
 * Created by yangsen on 2017/3/9.
 */
public class PriceCaculatorUtil {
    private static final Long HOUR = 60 * 60 * 1000L;
    private static final Long MINUTE = 60 * 1000L;

    public static String getPrice(Date startTime, Date endTime) {
        if (startTime.after(endTime)) {
            throw new IllegalArgumentException("参数错误，结束时间必须晚于开始时间");
        }
        BillingStrategy billingStrategy = new BillingStrategy(1, HOUR, 19, 1440 * 60 * 1000L, 129, 5 * 60 * 1000L, CarType.EV_330);
        double totalPrice = 0;
        long timeInterval = endTime.getTime() - startTime.getTime();
        if (timeInterval <= billingStrategy.getFreeTime()) {
            //如果用车少于免费周期
            totalPrice = billingStrategy.getPrice();
        } else {
            long hours = timeInterval / billingStrategy.getPeriod();
            long minutes = timeInterval % billingStrategy.getPeriod();
            long days = hours / 24;
            //计算第一部分价格：天数*每天的价格
            double daysPrice = 0;
            if (days > 0) {
                daysPrice = billingStrategy.getTopPrice() * days;
                hours = hours % 24;
            }
            //计算第二部分价格：小时*小时单价
            double hourPrice = hours * billingStrategy.getPrice();
            //计算第三部分价格：超过弹性时间时返回单价，否者返回0
            double minutePrice = minutes > billingStrategy.getFreeTime() ? billingStrategy.getPrice() : 0;
            //如果一天内价格超出了封顶价格则取一天的价格上限
            double innerDayPrice = hourPrice + minutePrice > billingStrategy.getTopPrice() ? billingStrategy.getTopPrice() : hourPrice + minutePrice;
            //最后总价等于两部分价格相加
            totalPrice = daysPrice + innerDayPrice;
        }
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        return decimalFormat.format(totalPrice);
    }

    public static void main(String[] args) {
        Date startTime = new Date(2017, 3, 9, 11, 0);
        Date endTime = new Date(2017, 3, 11, 11, 6);
        System.out.println(PriceCaculatorUtil.getPrice(startTime, endTime));
    }
}
